﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
namespace PwdClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var str = GetToken().Result;

            Console.WriteLine(str);
            var client = new HttpClient();

            Console.WriteLine("---------------需要密码授权------------------");

            client.SetBearerToken(str);
            var httpMessage = client.GetAsync("http://localhost:111/WeatherForecast").Result;
            var get = httpMessage.Content.ReadAsStringAsync().Result;
            Console.WriteLine($@"----{get}------");

            Console.WriteLine("-----------------------------------------");


        }

        private static async Task<string> GetToken()
        {
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:112");
            if (disco.IsError)
            {
                return disco.Error;
            }
            //客户端模式是：RequestClientCredentialsTokenAsync
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "client_pwd",
                ClientSecret = "secret_pwd",
                UserName = "test_admin",
                Password = "admin123456",
                Scope = "api1" //范围
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return tokenResponse.ErrorDescription;
            }
            return tokenResponse.AccessToken;
        }
    }
}
